package club.emergency.wechat.cors;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

/**
 * Create with IntelliJ IDEA
 * Project Name: business
 * Package Name: club.emergency.wechat_api.cors
 * Date: 2018/11/19
 *
 * @author: 快乐的小菌菌
 * Description: 跨域配置，如需要允许cookie的话需要在前端请求的时候单独设置一下
 */
@Configuration
public class CorsConfig {
    private CorsProperties corsProperties;

    public CorsConfig(CorsProperties corsProperties) {
        this.corsProperties = corsProperties;
    }

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin(corsProperties.getAllowOrigin());
        corsConfiguration.addAllowedHeader(corsProperties.getAllowHeader());
        corsConfiguration.addAllowedMethod(corsProperties.getAllowMethod());
        corsConfiguration.setMaxAge(corsProperties.getMaxAge());
        corsConfiguration.setExposedHeaders(Arrays.asList("Authorization"));
        corsConfiguration.setAllowCredentials(corsProperties.getAllowCredentials());

        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}
